﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Model;
using PMS.App_Code;

namespace PMS
{
    public partial class ViewDocTaskbyProject : System.Web.UI.Page
    {
        private DocTask doc;
        private Department dep;
        private UserInDepartment uid;
        private string projectID
        {
            get { return ViewState["projectID"].ToString(); }
            set { ViewState["projectID"] = value; }
        }

        public ViewDocTaskbyProject()
        {
            doc = new DocTask();
            dep = new Department();
            uid = new UserInDepartment();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                projectID = Request.QueryString["ProjectID"].ToString();
                //Session["ProjectID"] = projectID;
                BindLabel();
                BindDocTask();
                //Page.DataBind();
                Session["gvPageIndex"] = "True"; //设置Session["gvPageIndex"]为True
                BindNull();
            }
            //projectID = Session["ProjectID"].ToString();
        }

        protected void BindLabel()
        {
            Project p = new Project();
            ProjectInfo pi = p.LoadEntity(projectID);
            this.Label1.Text = projectID + " ( " + pi.ProjectName + " ) ";
        }

        protected void BindDocTask()
        {
            this.GridView1.DataSource = doc.GetDocTasksbyPID(projectID);
            this.GridView1.DataBind();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GridView1.PageIndex = e.NewPageIndex;
            BindDocTask();
        }

        //protected void LinkButton1_Click(object sender, EventArgs e)
        //{
        //    Response.Redirect("~/DocTask/DocTaskAdd.aspx?ProjectID=" + projectID);
        //}

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (User.Identity.Name == GridView1.DataKeys[e.RowIndex].Values[3].ToString())
            {
                int taskID = int.Parse(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
                doc.Delete(taskID, Page.User.Identity.Name);
                BindDocTask();
            }
            else
            {
                string str = "无权删除，只有相应的任务发布人能做此操作！";
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (((DetailsView)e.Row.FindControl("DetailsView1")) != null)
            {
                DetailsView d = (DetailsView)e.Row.FindControl("DetailsView1");
                if (((Label)d.Rows[1].Cells[1].FindControl("Label3")) != null)
                {
                    ((Label)d.Rows[1].Cells[1].FindControl("Label3")).Text = projectID;
                }
                if (((DropDownList)d.Rows[1].Cells[1].FindControl("DDLTaskName")) != null && ((DropDownList)d.Rows[2].Cells[1].FindControl("DDLProductTypeStep")) != null &&
                    ((DropDownList)d.Rows[5].Cells[1].FindControl("DDLDepartment")) != null && ((DropDownList)d.Rows[6].Cells[1].FindControl("DDLExecutor")) != null)
                {
                    DropDownList ddlTaskName = (DropDownList)d.Rows[1].Cells[1].FindControl("DDLTaskName");
                    ddlTaskName.DataSource = TaskName_Step.list;
                    ddlTaskName.DataTextField = "steptext";
                    ddlTaskName.DataValueField = "stepvalue";
                    ddlTaskName.DataBind();

                    DropDownList ddlProductTypeStep = (DropDownList)d.Rows[2].Cells[1].FindControl("DDLProductTypeStep");
                    ddlProductTypeStep.DataSource = ProjectProductType_Step.list;
                    ddlProductTypeStep.DataTextField = "steptext";
                    ddlProductTypeStep.DataValueField = "stepvalue";
                    ddlProductTypeStep.DataBind();

                    DropDownList ddlDepartment = (DropDownList)d.Rows[5].Cells[1].FindControl("DDLDepartment");
                    ddlDepartment.DataSource = dep.LoadEntities();
                    ddlDepartment.DataTextField = "DepartmentName";
                    ddlDepartment.DataValueField = "DepartmentID";
                    ddlDepartment.DataBind();
                    ddlDepartment.Items.Add(new ListItem("", "0"));

                    DropDownList ddlExecutor = (DropDownList)d.Rows[6].Cells[1].FindControl("DDLExecutor");
                    int departmentID = int.Parse(ddlDepartment.SelectedValue);
                    ddlExecutor.DataSource = uid.UserInDepartment_GetbyDID(departmentID);
                    ddlExecutor.DataTextField = "UserName";
                    ddlExecutor.DataValueField = "UserName";
                    ddlExecutor.DataBind();
                    if (ddlExecutor.Items.Count == 0)
                    {
                        ddlExecutor.Items.Add(new ListItem("", ""));
                    }
                }
            }
            if (e.Row.RowType == DataControlRowType.DataRow)//数据绑定行
            {
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)//正常交替状态行
                {
                    ((LinkButton)e.Row.Cells[18].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除!')");
                    if (DateTime.Parse(GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString()).Date == DateTime.Parse("1900-01-01 00:00:00").Date)
                    {
                        e.Row.Cells[9].Text = "";
                        e.Row.Cells[15].Text = "";
                    }
                    //if (e.Row.Cells[12].Text != "OPEN")
                    if (GridView1.DataKeys[e.Row.RowIndex].Values[2].ToString() != "OPEN" || GridView1.DataKeys[e.Row.RowIndex].Values[3].ToString() != User.Identity.Name)
                    {
                        e.Row.Cells[16].Enabled = false;
                        e.Row.Cells[17].Enabled = false;
                    }
                }
                if (GridView1.DataKeys[e.Row.RowIndex].Values[2].ToString() == "OPEN")
                {
                    e.Row.Cells[10].ForeColor = CommData.OPEN_COLOR;
                }
                try
                {
                    CheckBox che = (CheckBox)e.Row.FindControl("Checkbox1");
                    che.Attributes.Add("onclick", "ChangeGet(this)");
                }
                catch { }
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Insert")
            {
                GridView1.DataSource = null;
                GridView1.DataBind();
            }
        }

        protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
        {
            DetailsView d = (DetailsView)this.GridView1.Controls[0].Controls[0].FindControl("DetailsView1");
            DocTaskInfo dti = new DocTaskInfo();
            dti.TaskID = 1;
            //dti.ProjectID = projectID;
            dti.ProjectID = ((Label)d.Rows[0].Cells[1].FindControl("Label3")).Text.Trim();
            if (!string.IsNullOrEmpty(((DropDownList)(d.Rows[1].Cells[1].FindControl("DDLTaskName"))).SelectedValue))
            {
                dti.TaskName = ((DropDownList)(d.Rows[1].Cells[1].FindControl("DDLTaskName"))).SelectedValue;
            }
            else
            {
                dti.TaskName = ((TextBox)(d.Rows[1].Cells[1].FindControl("TbTaskName"))).Text.Trim();
            }
            dti.ProductTypeStep = ((DropDownList)(d.Rows[2].Cells[1].FindControl("DDLProductTypeStep"))).SelectedValue;
            dti.RecordTime = DateTime.Now;
            dti.Publisher = User.Identity.Name;
            dti.BeginTime = DateTime.Parse(((TextBox)(d.Rows[3].Cells[1].FindControl("TextBox1"))).Text.Trim());
            dti.PostTime = DateTime.Parse(((TextBox)(d.Rows[4].Cells[1].FindControl("TextBox2"))).Text.Trim());
            dti.Department = ((DropDownList)(d.Rows[5].Cells[1].FindControl("DDLDepartment"))).SelectedItem.Text;
            dti.Executor = ((DropDownList)(d.Rows[6].Cells[1].FindControl("DDLExecutor"))).SelectedValue;
            dti.TaskDetail = ((TextBox)(d.Rows[7].Cells[1].FindControl("TBXTaskDetail"))).Text.Trim();
            string str = "";
            try
            {
                doc.Insert(dti, Page.User.Identity.Name);
                str = "任务发布成功！";
                GridView1.DataSource = null;
                GridView1.DataBind();
            }
            catch
            {
                str = "任务发布失败，请联系相关人员！";
            }
            finally
            {
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
            }
        }

        protected void DetailsView1_ModeChanging(object sender, DetailsViewModeEventArgs e)
        {
            BindDocTask();
        }

        protected void DDLDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddlDepartment = sender as DropDownList;
            DropDownList ddlExecutor = (DropDownList)((ddlDepartment.NamingContainer as DetailsView).Rows[6].Cells[1].FindControl("DDLExecutor"));
            int departmentID = int.Parse(ddlDepartment.SelectedValue);
            ddlExecutor.DataSource = uid.UserInDepartment_GetbyDID(departmentID);
            ddlExecutor.DataTextField = "UserName";
            ddlExecutor.DataValueField = "UserName";
            ddlExecutor.DataBind();
        }

        /// <summary>
        /// GridView2的操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GridView2.PageIndex = e.NewPageIndex;
            BindDocTaskClose();
        }

        protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)//数据绑定行
            {
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)//正常交替状态行
                {
                    if (DateTime.Parse(GridView2.DataKeys[e.Row.RowIndex].Values[1].ToString()).Date == DateTime.Parse("1900-01-01 00:00:00").Date)
                    {
                        e.Row.Cells[9].Text = "";
                        e.Row.Cells[15].Text = "";
                    }
                }
                if (GridView2.DataKeys[e.Row.RowIndex].Values[2].ToString() == "DELAYCLOSED")
                {
                    e.Row.Cells[10].ForeColor = CommData.DELAYCLOSED_COLOR;
                }
            }
        }

        /// <summary>
        /// 已完结任务列表
        /// </summary>
        protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (this.CheckBox1.Checked)
            {
                BindDocTaskClose();
            }
            else
            {
                BindNull();
            }
        }

        protected void BindNull()
        {
            this.GridView2.DataSource = null;
            this.GridView2.DataBind();
        }

        protected void BindDocTaskClose()
        {
            this.GridView2.DataSource = doc.GetDocTasksbyPIDClose(projectID);
            this.GridView2.DataBind();
        }

        /// <summary>
        ///添加新任务 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            GridView1.DataSource = null;
            GridView1.DataBind();
        }

        /// <summary>
        /// 删除选中任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox chk = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
                if (chk != null && chk.Checked)
                {
                    int docID = int.Parse(GridView1.DataKeys[i].Values[0].ToString());
                    if (User.Identity.Name == GridView1.DataKeys[i].Values[3].ToString())
                    {
                        try
                        {
                            doc.Delete(docID, Page.User.Identity.Name);
                            BindDocTask();
                        }
                        catch
                        {
                            string str = "选中任务删除失败，请联系相关人员！";
                            ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
                        }
                    }
                    else
                    {
                        string str = "无权删除，只有相应的任务发布人能做此操作！";
                        ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
                    }
                    //只有一个选中行
                    return;
                }
            }
        }
    }
}